package cn.jolyoulu.cmnservice.serivce.impl;

import cn.jolyoulu.common.redis.utils.RedisUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.jolyoulu.cmnservice.constant.ServiceRedisConstant;
import cn.jolyoulu.cmnservice.dao.SysDictDataMapper;
import cn.jolyoulu.cmnservice.entity.po.SysDictData;
import cn.jolyoulu.cmnservice.serivce.SysDictDataService;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements SysDictDataService {

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private RedisUtils redisUtil;

    @Override
    public boolean removeByDictTypeId(String dictTypeId) {
        LambdaQueryWrapper<SysDictData> ew = new LambdaQueryWrapper<>();
        ew.eq(SysDictData::getDictTypeId,dictTypeId);
        return sysDictDataMapper.delete(ew) > 0;
    }

    @Override
    public List<SysDictData> selectByDictTypeId(String dictTypeId) {
        String key = ServiceRedisConstant.getDictListDicttype(dictTypeId);
        List<SysDictData> cache = (List<SysDictData>) redisUtil.get(key);
        if (Objects.isNull(cache)){
            LambdaQueryWrapper<SysDictData> ew = new LambdaQueryWrapper<>();
            ew.eq(SysDictData::getDictTypeId,dictTypeId);
            ew.orderByDesc(SysDictData::getSort);
            cache = sysDictDataMapper.selectList(ew);
            if (Objects.nonNull(cache)){
                redisUtil.set(key,cache,1, TimeUnit.DAYS);
            }
        }
        return cache;
    }

    @Override
    public SysDictData getByDictTypeIdAndDictValue(String dictTypeId, String dictValue) {
        LambdaQueryWrapper<SysDictData> ew = new LambdaQueryWrapper<>();
        ew.eq(SysDictData::getDictTypeId,dictTypeId);
        ew.eq(SysDictData::getDictValue,dictTypeId);
        return sysDictDataMapper.selectOne(ew);
    }
}